<?php
class login extends ujn_controller {
	var $auto_render = false;
	var $view_type = 'json';
	

	private function _auth($txt, $operation = 'ENCODE', $key = '') {
		$key    = $key ? $key : ujn::get_cfg('system.auth_key'); // , '9qZGplPV6gme9CCWz2Iz'
		$txt    = $operation == 'ENCODE' ? (string)$txt : base64_decode($txt);
		$len    = strlen($key);
		$code   = '';
		for($i=0; $i<strlen($txt); $i++){
			$k     = $i % $len;
			$code  .= $txt[$i] ^ $key[$k];
		}
		$code = $operation == 'DECODE' ? $code : base64_encode($code);
		return $code;
	}
	
	private function _get($var, $default = '') {
		$var = ujn::get_cfg('system.cookie_pre') . $var; // , 'iIUyh_'
		return isset($_COOKIE[$var]) ? $this->_auth($_COOKIE[$var], 'DECODE') : $default;
	}
	function check() {
		$o = array( 's' => 0 );
		$uname = $this->_get('_username');
		if(!empty($uname)) {
			$o['s'] = 1;
			$o['username'] = $uname;
		}
		// $o['c'] = $_COOKIE;
		return $o;
	}
	
	function load_comment() {
		$id = $this->get('id');
		$siteid = $this->get('siteid', 1);
		$pg = $this->get('pg', 1);
		$cnt = mdl_comments::get_instance()->find_count($id, $siteid);
		$max = 3;
		return array(
				'cnt' => $cnt,
				'datas' => mdl_comments::get_instance()->find($id, $siteid, --$pg * $max, $max)
				);
	}
	
	function post_comment() {
		$id = $this->post('id');
		$content = $this->post('content');
		$username = $this->_get('_username', '可可网友');
		$userid = $this->_get('_userid', '0');
		
		$o = array( 's' => 0 );
		$o['s'] = (int)mdl_comments::get_instance()->append($id, $userid, $username, $content);
		
		return array();
	}
	
	function support_comment() {
		$o = array( 's' => 0 );
		$id = $this->get('id', 0);
		$o['s'] = (int)mdl_comments::get_instance()->support($id);
		return $o;
	}
}










// cookie_pre' => 'iIUyh_
// auth_key' => '9qZGplPV6gme9CCWz2Iz

// function set_cookie($var, $value = '', $time = 0) {
// 	$time = $time > 0 ? $time : ($value == '' ? SYS_TIME - 3600 : 0);
// 	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
// 	$var = pc_base::load_config('system','cookie_pre').$var;
// 	$_COOKIE[$var] = $value;
// 	if (is_array($value)) {
// 		foreach($value as $k=>$v) {
// 			setcookie($var.'['.$k.']', sys_auth($v, 'ENCODE'), $time, pc_base::load_config('system','cookie_path'), pc_base::load_config('system','cookie_domain'), $s);
// 		}
// 	} else {
// 		setcookie($var, sys_auth($value, 'ENCODE'), $time, pc_base::load_config('system','cookie_path'), pc_base::load_config('system','cookie_domain'), $s);
// 	}
// }
